package com.proyecto.robomind.map;

import com.proyecto.robomind.R;
import com.proyecto.robomind.interpreter.FileManager;
import com.proyecto.robomind.model.MapSquare;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MapLayout extends Activity{

    private FileManager mDbHelper;
    private MainMapPanel mapPanel;
    
    private Long mapId;

	private EditText mTitleText;
    private TextView charSelTv;
    private LinearLayout mapLayout;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mDbHelper = new FileManager(this.getApplicationContext());
        mDbHelper.open();
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);  
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        setContentView(R.layout.main_map_layout); 
        
        charSelTv = (TextView) findViewById(R.id.characterSelectedtv);
        
        mTitleText = (EditText) findViewById(R.id.title);
        
        mapLayout = (LinearLayout) findViewById(R.id.mapLayout);
        mapPanel = new MainMapPanel(this.getApplicationContext());
        mapLayout.addView(mapPanel);
    }
	
	  @Override
	    protected void onPause() {
	        super.onPause();
	        saveState();
	       	mapPanel.setThreadRunning(false);
	    }

	    @Override
	    protected void onResume() {
	        super.onResume();
	       	mapPanel.setThreadRunning(true);
	    }
	
	public void newMap(View v){
		createNewMapDialog();
	}
	
	public void saveMap(View v){
		if(mapPanel.getCurrentMap()!=null){
			saveState();
		}
	}
	
	public void loadMap(View v){
		createMapDialog();
	}
	
	public void characterSelection(View v){
		switch(v.getId()){
		case R.id.blockBtn:
			mapPanel.setCharacter("b");
			break;
		case R.id.bushBtn:
			mapPanel.setCharacter("h");
			break;
		case R.id.fenceBtn:
			mapPanel.setCharacter("f");
			break;
		case R.id.rocksBtn:
			mapPanel.setCharacter("r");
			break;
		case R.id.treeBtn:
			mapPanel.setCharacter("t");
			break;
		case R.id.staffBtn:
			mapPanel.setCharacter("s");
			break;
		case R.id.originBtn:
			if(MapHandler.hasOrigin(mapPanel.getCurrentMap())){
				mapPanel.setCharacter("e");
				Toast.makeText(this, "Map cannot have two origins.",Toast.LENGTH_SHORT).show();
			}else{
				mapPanel.setCharacter("o");	
			}
			break;
		case R.id.emptyBtn:
			mapPanel.setCharacter("e");
			break;
		}
		charSelTv.setText("Character Selected: " + mapPanel.getCharacter().toUpperCase());
	}
	
    public void loadMap(Long mapId){
    	if (mapId != null) {
            Cursor map = mDbHelper.fetchMap(mapId);
            startManagingCursor(map);
            
            MapSquare[][] ms = MapHandler.concatenizeMap(map.getString(map.getColumnIndexOrThrow(FileManager.KEY_MAP)), mapLayout.getHeight(), mapLayout.getWidth());
            
            mapPanel.loadMap(ms);
            
            mTitleText.setText(map.getString(map.getColumnIndexOrThrow(FileManager.KEY_TITLE)));
    	}
    }
	
    private void saveState() {
    	if(mapPanel.isMapLoaded()){
	        String title = mTitleText.getText().toString();
	
	        if(title.equals("")){
	        	title = "No title";
	        }
	
	        if (mapId == null) {
	            long id = mDbHelper.createMap(title, MapHandler.unconcatenizeMap(mapPanel.getCurrentMap()));
	            Log.d("Map string", MapHandler.unconcatenizeMap(mapPanel.getCurrentMap()));
	            if (id > 0) {
	                mapId = id;
	            }
	        } else {
	            mDbHelper.updateMap(mapId, title, MapHandler.unconcatenizeMap(mapPanel.getCurrentMap()));
	        }

			Toast.makeText(this, "Map saved succesfully",Toast.LENGTH_SHORT).show();
    	}else{
			Toast.makeText(this, "No map on screen",Toast.LENGTH_SHORT).show();
    	}
    }
    
	public void createNewMapDialog(){
		final MapCreationLayout layout = new MapCreationLayout(this);
	    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	    alertDialog.setView(layout);
	    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		dialog.dismiss();
	    } });

	    alertDialog.setButton("Create", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		if(layout.isInputCorrect()){	
	    			dialog.dismiss();
	    			mapPanel.createNewMap(layout.getHeightCoord(), layout.getWidthCoord(), mapLayout.getHeight(), mapLayout.getWidth());
	    		}
	    } });
	    alertDialog.show();
	}
	
	public ListView fillMapList(){
		Cursor notesCursor = mDbHelper.fetchAllMaps();
        startManagingCursor(notesCursor);

        String[] from = new String[]{FileManager.KEY_TITLE};
        int[] to = new int[]{R.id.text1};

        SimpleCursorAdapter notes = 
            new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
        ListView lv = new ListView(this);
        lv.setAdapter(notes);
        lv.setBackgroundColor(Color.WHITE);
        return lv;
   }
   
	public void createMapDialog(){
		mapId = null;
	    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	    alertDialog.setView(createMapList());
	    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		dialog.dismiss();
	    } });
	    alertDialog.setButton3("Delete", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		if(mapId != null){
	    			dialog.dismiss();
	    			mDbHelper.deleteMap(mapId);
	    		}
	    } });
	    
	    alertDialog.setButton("Load", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int which) {
	    		if(mapId != null){
	    			dialog.dismiss();
	    			loadMap(mapId);
	    		}
	    } });
	    alertDialog.show();
	}
	
	public ListView createMapList(){
		ListView modeList = fillMapList();
		modeList.setBackgroundColor(Color.WHITE);
	    modeList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				mapId = id;
			}
		});
	    return modeList;
	}
	
}
